//
//  LoopHomeViewModel.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/11.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class LoopHomeViewModel: NSObject {

    lazy var statusModelArray:[LoopStatusCellViewModel] = [LoopStatusCellViewModel]()
    //获取数据
    func loadHomeData(isPull:Bool,finish:@escaping (Bool,Int)->()){
        
        var max_id:Int64 = 0
        var since_id:Int64 = 0
        
        if isPull {
            max_id = statusModelArray.last?.statusModel?.id ?? 0
            if max_id != 0 {
                max_id -= 1
            }
        }else{
        
            since_id = statusModelArray.first?.statusModel?.id ?? 0
        }
        
        LoopStatusDAL.loadHomeData(since_id: since_id, max_id: max_id,isPull:isPull) { (array) in
            if array == nil{
                finish(false,0)
                return
            }
            //创建空数组存储数据
            var tempArray = [LoopStatusCellViewModel]()
            for dict in array! {
                
                let model = LoopStatusCellViewModel()
                let status = LoopStatus()
                
                //使用yymodel框架给模型赋值
                status.yy_modelSet(with: dict)
                model.statusModel = status
                
//                //根据数据选择对应的cell
//                let cell = self.loadCell(viewModel: model)
//                //给cell赋值
//                cell.viewModel = model
//                //刷新cell控件布局
//                cell.layoutIfNeeded()
//                //将高度赋给model
//                model.rowHeight = cell.showdView.frame.maxY
                
                tempArray.append(model)
                
            }
            if isPull{
                //上拉刷新的数据
                self.statusModelArray = self.statusModelArray + tempArray
            }else{
                //第一次刷新和下拉刷新的数据
                self.statusModelArray = tempArray + self.statusModelArray
            }
            //            let count = tempArray.count
            //            finish(true,count)
            //            self.cacheSinglePicture(tempArray: tempArray)
            self.cacheSinglePicture(tempArray: tempArray, finish: finish)
        }

    }
    
    
    private func cacheSinglePicture(tempArray:[LoopStatusCellViewModel],finish:@escaping (Bool,Int)->()){
        
        //判断,防止崩溃
        if tempArray.count == 0 {
            finish(true,0)
            return
        }
        
        //遍历数组,当图片个数为一时,缓存
        //使用调度组,保证图片全部下载完成之后再执行回调,刷新数据
        let group = DispatchGroup()
        for cellModel in tempArray {
            if cellModel.imageArray?.count == 1 {
                group.enter()
                let url = cellModel.imageArray?.last?.imageUrl
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
//                    print("success")
                    group.leave()
                })
            }
        }
        //调度组内任务执行完毕,需要通知执行后续操作
        group.notify(queue: DispatchQueue.main) {
            //根据数据选择对应的cell
            
            for model in tempArray{
                let cell = self.loadCell(viewModel: model)
                //给cell赋值
                cell.viewModel = model
                //刷新cell控件布局
                cell.layoutIfNeeded()
                //将高度赋给model
                model.rowHeight = cell.showdView.frame.maxY
            }
            
            finish(true,tempArray.count)
        }
    }

    private func loadCell(viewModel:LoopStatusCellViewModel)->LoopHomeTableViewCell{
        return (viewModel.statusModel?.retweeted_status != nil ? retweetedTableCell : homeTableCell)
    
    }
    
}
